<?php
/**
 *登录
 */

namespace App\Http\Controllers;

use Mail, Captcha;
use App\Http\Model\User as UserModel;
use App\Http\Model\UserLoginLog as UserLoginLogModel;
use Illuminate\Http\Request;

class LoginController extends Controller
{
    protected $request;
    protected $userModel;
    protected $userLoginLogModel;

    public function __construct(Request $request)
    {
        parent::__construct();

        $this->request = $request;
        $this->userModel         = new UserModel();
        $this->userLoginLogModel = new UserLoginLogModel();
    }

    /**
     * 登录
     * @return \Illuminate\Contracts\Routing\ResponseFactory|\Illuminate\Contracts\View\Factory|\Illuminate\View\View|\Symfony\Component\HttpFoundation\Response
     */
    public function login()
    {
        if ($this->request->isMethod('post')) {
            try {
                if ($this->request->has('account')) {

                    if (!Captcha::check($this->request->input('captcha'))) {
                        throw new \Exception('验证码输入错误！');
                    }

                    $res_bool = $this->userModel->vaildAccountPassword($this->request->input('account'), $this->request->input('password'));
                    if (!$res_bool) {
                        throw new \Exception('账号或密码不正确！');
                    }

                    //登录成功
                    $user_info = $this->userModel->getUserInfoByAccount($this->request->input('account'));

                    //保存登录信息
                    $this->request->session()->put('x-account', $this->request->input('account'));
                    $this->request->session()->put('x-user-id', $user_info['id']);

                    //写入登录日志
                    $res = $this->userLoginLogModel->addUserLoginLog($user_info['id'], $this->request->ip(), 1);
                    if (!$res) {
                        throw new \Exception('保存登录日志失败！');
                    }

                } elseif ($this->request->has('email')) {
                    if ((string)decrypt($this->request->session()->get('login_email_code')) != $this->request->input('email_code')) {
                        throw new \Exception('验证码不正确！');
                    }

                    if (!$this->userModel->vaildEmailExists($this->request->input('email'))) {
                        throw new \Exception('邮箱或验证码不正确！');
                    }

                    //保存登录信息
                    $user_info = $this->userModel->getUserInfoByAccount($this->request->input('email'));
                    $this->request->session()->put('x-account', $this->request->input('email'));
                    $this->request->session()->put('x-user-id', $user_info['id']);
                    $this->request->session()->forget('login_email_code');

                    //写入登录日志
                    $res = $this->userLoginLogModel->addUserLoginLog($user_info['id'], $this->request->ip(), 2);
                    if (!$res) {
                        throw new \Exception('保存登录日志失败！');
                    }
                }

                return response(['code' => 1, 'msg' => '登录成功！']);
            } catch (\Exception $e) {
                return response(['code' => 0, 'msg' => $e->getMessage()]);
            }
        }
        return view('admin.login');
    }

    /**
     * 发送邮件验证码
     * @return \Illuminate\Contracts\Routing\ResponseFactory|\Symfony\Component\HttpFoundation\Response
     */
    public function sendEmailCode()
    {
        $email      = $this->request->input('email');
        $email_code = mt_rand(100000, 999999);

        try {
            Mail::send('email.login_email_code', ['email_code' => $email_code], function ($mail) use ($email) {
                $mail->from(config('mail.username'), config('app.name'));
                $mail->to($email)->subject('邮件验证码登录');
            });

            if (count(Mail::failures()) > 0) {
                throw new \Exception('发送邮件验证码失败！');
            }
            $this->request->session()->put('login_email_code', encrypt($email_code));

            return response(['code' => 1, 'msg' => '发送成功！']);
        } catch (\Exception $e) {
            return response(['code' => 0, 'msg' => $e->getMessage()]);
        }
    }

    /**
     * 注销
     * @return \Illuminate\Contracts\Routing\ResponseFactory|\Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector|\Symfony\Component\HttpFoundation\Response
     */
    public function logout()
    {
        $user_id = $this->request->session()->pull('x-user-id');
        $this->userLoginLogModel->updateUserLoginLogLast($user_id, ['logout_at' => date('Y-m-d H:i:s', time())]);
        $this->request->session()->forget('x-account');

        if ($this->request->isMethod('post')) {
            return response(['code' => 1, 'msg' => '注销成功！']);
        }

        return redirect('/login');
    }
}
